'use client'

import React, { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Save, Lock, Eye, EyeOff, AlertCircle, CheckCircle } from 'lucide-react'
import { useParameterPermissions } from '@/hooks/use-parameter-permissions'
import { useAuth } from '@/hooks/use-auth'
import { useToast } from '@/hooks/use-toast'

interface ParameterEditorProps {
  tableName: string
  deviceId: number
  deviceName: string
  onSave?: () => void
}

export function ParameterEditorWithPermissions({
  tableName,
  deviceId,
  deviceName,
  onSave
}: ParameterEditorProps) {
  const [saving, setSaving] = useState(false)
  const [showAllFields, setShowAllFields] = useState(false)
  const [selectedSpecialty, setSelectedSpecialty] = useState<string>('my') // 'my', 'all', 'procurement', 'design', 'monitoring', 'construction', 'operations'
  const { toast } = useToast()

  const {
    fields,
    loading,
    error,
    editData,
    user,
    permissions,
    updateFieldValue,
    saveParameters,
    getFieldsByDataSource,
    getEditableFieldsCount,
    getVisibleFieldsCount,
    getUserDataSources,
    canEditField
  } = useParameterPermissions(tableName, deviceId)

  // 直接从 useAuth 获取 hasDataSourceAccess 函数
  const { hasDataSourceAccess } = useAuth(tableName)

  // 获取当前用户的默认专业
  const getUserDefaultSpecialty = React.useCallback(() => {
    if (!user || !permissions) return 'my'

    const roleSpecialtyMap: Record<string, string> = {
      'P': 'procurement',
      'E': 'design',
      'M': 'monitoring',
      'C': 'construction',
      'O': 'build',
      'R': 'operations',
      'A': 'all',
      'V': 'all'
    }

    return roleSpecialtyMap[user.role_code] || 'my'
  }, [user, permissions])

  // 初始化默认专业选择
  React.useEffect(() => {
    if (user && selectedSpecialty === 'my') {
      const defaultSpecialty = getUserDefaultSpecialty()
      if (defaultSpecialty !== 'my') {
        setSelectedSpecialty(defaultSpecialty)
      }
    }
  }, [user, getUserDefaultSpecialty, selectedSpecialty])

  const handleSave = async () => {
    try {
      setSaving(true)
      await saveParameters()
      toast({
        title: "保存成功",
        description: "参数已成功保存",
      })
      onSave?.()
    } catch (error) {
      console.error('保存失败:', error)
      toast({
        title: "保存失败",
        description: error instanceof Error ? error.message : "保存参数失败",
        variant: "destructive",
      })
    } finally {
      setSaving(false)
    }
  }

  const getDataSourceName = (source: string) => {
    const names: Record<string, string> = {
      'P': '采购',
      'E': '设计',
      'M': '监测',
      'O': '建设',
      'C': '施工',
      'R': '运维'
    }
    return names[source] || source
  }

  const getSpecialtyName = (specialty: string) => {
    const names: Record<string, string> = {
      'my': '我的专业',
      'all': '全部',
      'procurement': '采购',
      'design': '设计',
      'monitoring': '监测',
      'construction': '施工',
      'operations': '运维'
    }
    return names[specialty] || specialty
  }

  const getSpecialtyDataSources = (specialty: string): string[] => {
    const mapping: Record<string, string[]> = {
      'my': getUserDataSources(),
      'all': allAvailableDataSources,
      'procurement': ['P'],
      'design': ['E'],
      'monitoring': ['M'],
      'construction': ['C'],
      'operations': ['O', 'R']
    }
    return mapping[specialty] || []
  }

  const getDataSourceDescription = (source: string) => {
    const descriptions: Record<string, string> = {
      'P': '采购部门负责的设备采购相关参数',
      'E': '设计部门负责的工程设计相关参数',
      'M': '监测部门负责的监测相关参数',
      'O': '建设部门负责的建设相关参数',
      'C': '施工部门负责的施工相关参数',
      'R': '运维阶段的运维相关参数'
    }
    return descriptions[source] || source
  }

  const getDataSourceColor = (source: string) => {
    const colors: Record<string, string> = {
      'P': 'bg-blue-100 text-blue-800',
      'E': 'bg-green-100 text-green-800',
      'M': 'bg-orange-100 text-orange-800',
      'O': 'bg-purple-100 text-purple-800'
    }
    return colors[source] || 'bg-gray-100 text-gray-800'
  }

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/3 mb-4"></div>
          <div className="space-y-3">
            {[1, 2, 3, 4, 5].map(i => (
              <div key={i} className="h-16 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    )
  }

  const userDataSources = getUserDataSources()
  const editableCount = getEditableFieldsCount()
  const visibleCount = getVisibleFieldsCount()

  // 获取所有可用的数据来源（基于数据库中实际存在的数据来源）
  const allAvailableDataSources = ['C', 'E', 'P', 'R'].sort()

  // 根据选择的专业获取对应的数据来源
  const filteredDataSources = getSpecialtyDataSources(selectedSpecialty)

  // 调试信息 - 使用简单的 console.log 而不是 useEffect
  if (process.env.NODE_ENV === 'development') {
    console.log('=== 专业切换调试 ===')
    console.log('选择的专业:', selectedSpecialty)
    console.log('对应的数据来源:', filteredDataSources)
    console.log('所有字段数量:', fields.length)
    console.log('所有可用数据来源:', allAvailableDataSources)
    console.log('用户信息:', user)
    console.log('权限信息:', permissions)
    console.log('可编辑字段数:', editableCount)
    console.log('可见字段数:', visibleCount)

    // 检查hasDataSourceAccess函数
    if (user && permissions) {
      console.log('权限检查:')
      console.log('  - hasDataSourceAccess(E):', hasDataSourceAccess('E'))
      console.log('  - hasDataSourceAccess(P):', hasDataSourceAccess('P'))
      console.log('  - hasDataSourceAccess(C):', hasDataSourceAccess('C'))
      console.log('  - hasDataSourceAccess(R):', hasDataSourceAccess('R'))
      console.log('  - 用户角色代码:', user.role_code)
      console.log('  - 权限配置:', permissions)
    }

    // 详细检查每个字段的权限状态
    console.log('=== 字段权限详细检查 ===')
    fields.forEach(field => {
      console.log(`字段: "${field.field_name}" | 数据来源: ${field.data_source} | 可编辑: ${field.canEdit} | 可见: ${field.isVisible}`)
    })

    filteredDataSources.forEach(source => {
      const sourceFields = getFieldsByDataSource(source)
      console.log(`数据来源 ${source}:`, sourceFields.length, '个字段')
      sourceFields.forEach(field => {
        console.log(`  - "${field.field_name}" (可见:${field.isVisible}, 可编辑:${field.canEdit})`)
      })
    })
    console.log('=== 调试结束 ===')
  }

  return (
    <div className="space-y-6">
      {/* 权限信息卡片 */}
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <CardTitle className="text-lg">参数编辑权限</CardTitle>
            <div className="flex items-center space-x-2">
              {/* 专业选择下拉框 */}
              <div className="flex items-center space-x-2">
                <label className="text-sm font-medium text-gray-600">专业:</label>
                <select
                  value={selectedSpecialty}
                  onChange={(e) => setSelectedSpecialty(e.target.value)}
                  className="px-3 py-2 border rounded-md text-sm bg-white min-w-[120px]"
                >
                  <option value="all">全部</option>
                  <option value="design">设计</option>
                  <option value="procurement">采购</option>
                  <option value="construction">施工</option>
                  <option value="build">建设</option>
                  <option value="operations">运维</option>
                  <option value="monitoring">监测</option>
                </select>
              </div>

              {process.env.NODE_ENV === 'development' && (
                <button
                  onClick={() => window.location.reload()}
                  className="px-3 py-2 bg-blue-500 text-white rounded text-xs hover:bg-blue-600"
                >
                  刷新权限
                </button>
              )}

              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowAllFields(!showAllFields)}
              >
                {showAllFields ? <EyeOff className="h-4 w-4 mr-2" /> : <Eye className="h-4 w-4 mr-2" />}
                {showAllFields ? '隐藏空字段' : '显示所有字段'}
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            <div>
              <div className="text-sm font-medium text-gray-600">当前用户</div>
              <div className="text-lg font-semibold">{user?.full_name}</div>
              <Badge className="mt-1">{user?.role_name}</Badge>
            </div>
            <div>
              <div className="text-sm font-medium text-gray-600">当前专业</div>
              <div className="text-lg font-semibold text-blue-600">
                {getSpecialtyName(selectedSpecialty)}
              </div>
              <div className="text-xs text-gray-500">
                {selectedSpecialty === 'all' ? '显示所有专业数据' : `显示${getSpecialtyName(selectedSpecialty)}专业相关字段`}
              </div>
            </div>
            <div>
              <div className="text-sm font-medium text-gray-600">可编辑字段</div>
              <div className="text-lg font-semibold text-green-600">{editableCount}</div>
              <div className="text-xs text-gray-500">共 {visibleCount} 个字段</div>
            </div>
            <div>
              <div className="text-sm font-medium text-gray-600">我的专业权限</div>
              <div className="flex flex-wrap gap-1 mt-1">
                {userDataSources.map(source => (
                  <Badge key={source} className={getDataSourceColor(source)}>
                    {getDataSourceName(source)}
                  </Badge>
                ))}
              </div>
            </div>
            <div>
              <div className="text-sm font-medium text-gray-600">设备信息</div>
              <div className="text-lg font-semibold">{deviceName}</div>
              <div className="text-xs text-gray-500">ID: {deviceId}</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 按数据来源分组的参数编辑 */}
      <Card>
        <CardHeader>
          <CardTitle>参数编辑</CardTitle>
        </CardHeader>
        <CardContent>
          {filteredDataSources.length > 0 ? (
            <Tabs defaultValue="all" className="w-full">
              <TabsList className={`grid w-full grid-cols-${Math.min(filteredDataSources.length + 1, 6)}`}>
                <TabsTrigger key="all" value="all">
                  <div className="flex items-center space-x-1">
                    <span>全部</span>
                  </div>
                </TabsTrigger>
                {filteredDataSources.map(source => (
                  <TabsTrigger key={source} value={source}>
                    <div className="flex items-center space-x-1">
                      <span>{getDataSourceName(source)}</span>
                      {!hasDataSourceAccess(source) && (
                        <Lock className="h-3 w-3 text-gray-400" title="只读权限" />
                      )}
                    </div>
                  </TabsTrigger>
                ))}
              </TabsList>

            {/* 全部标签页 - 显示所有字段 */}
            <TabsContent key="all" value="all" className="space-y-4">
              <div className="flex justify-between items-center">
                <div>
                  <h3 className="text-lg font-medium flex items-center space-x-2">
                    <span>全部专业数据</span>
                  </h3>
                  <p className="text-sm text-gray-500 mt-1">
                    显示所有专业的字段数据
                    <span className="ml-2">
                      ({fields.filter(f => f.canEdit).length} 可编辑 / {fields.filter(f => f.isVisible).length} 显示)
                    </span>
                  </p>
                </div>
              </div>

              {fields.filter(f => f.isVisible).length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>字段名称</TableHead>
                      <TableHead>描述</TableHead>
                      <TableHead>数据来源</TableHead>
                      <TableHead>数据类型</TableHead>
                      <TableHead>计量单位</TableHead>
                      <TableHead>当前值</TableHead>
                      <TableHead>状态</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {fields.filter(f => f.isVisible).map((field) => (
                      <TableRow key={field.id} className={field.canEdit ? "bg-green-50" : ""}>
                        <TableCell className="font-medium">
                          <div className="flex items-center gap-2">
                            {field.canEdit && <span className="text-green-600 text-sm">✓</span>}
                            {Array.isArray(field.field_name) ? field.field_name[0] : field.field_name}
                          </div>
                        </TableCell>
                        <TableCell className="text-sm text-gray-600">
                          {field.field_description}
                        </TableCell>
                        <TableCell>
                          <Badge className={getDataSourceColor(field.data_source)}>
                            {field.data_source}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">{field.data_type}</Badge>
                        </TableCell>
                        <TableCell>{field.measurement_unit}</TableCell>
                        <TableCell>
                          {field.canEdit ? (
                            <Input
                              value={editData[field.id] || ''}
                              onChange={(e) => updateFieldValue(field.id, e.target.value)}
                              placeholder={field.example_description}
                              className="w-full"
                            />
                          ) : (
                            <div className="flex items-center space-x-2 text-gray-500">
                              <span className="text-sm">
                                {editData[field.id] || field.parameter_value || '-'}
                              </span>
                              <Lock className="h-4 w-4 text-gray-400" />
                            </div>
                          )}
                        </TableCell>
                        <TableCell>
                          {field.canEdit ? (
                            <Badge variant="default" className="bg-green-100 text-green-800">
                              <CheckCircle className="h-3 w-3 mr-1" />
                              可编辑
                            </Badge>
                          ) : (
                            <Badge variant="secondary" className="bg-gray-100 text-gray-600">
                              <Lock className="h-3 w-3 mr-1" />
                              只读
                            </Badge>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    没有可显示的字段数据
                  </AlertDescription>
                </Alert>
              )}
            </TabsContent>

            {filteredDataSources.map(source => {
              const sourceFields = getFieldsByDataSource(source)
              const userHasSourceAccess = hasDataSourceAccess(source)

              // 显示该数据源的所有字段，权限控制在编辑层面
              const displayFields = sourceFields
                .filter(f => f.isVisible)
                .sort((a, b) => {
                  // 首先按照是否可编辑排序（可编辑的在前）
                  if (a.canEdit !== b.canEdit) {
                    return a.canEdit ? -1 : 1;
                  }
                  // 然后按照原始字段顺序排序
                  return a.field_sequence - b.field_sequence;
                })
              
              return (
                <TabsContent key={source} value={source} className="space-y-4">
                  <div className="flex justify-between items-center">
                    <div>
                      <h3 className="text-lg font-medium flex items-center space-x-2">
                        <span>{getDataSourceName(source)}专业数据</span>
                        {!userHasSourceAccess && (
                          <Badge variant="secondary" className="text-xs">
                            <Lock className="h-3 w-3 mr-1" />
                            只读权限
                          </Badge>
                        )}
                      </h3>
                      <p className="text-sm text-gray-500 mt-1">
                        {getDataSourceDescription(source)}
                        <span className="ml-2">
                          ({displayFields.filter(f => f.canEdit).length} 可编辑 / {displayFields.length} 显示)
                        </span>
                      </p>
                    </div>
                  </div>
                  
                  {displayFields.length === 0 ? (
                    <Alert>
                      <AlertCircle className="h-4 w-4" />
                      <AlertDescription>
                        {userHasSourceAccess
                          ? '当前显示模式下没有可显示的字段'
                          : `您没有权限编辑${getDataSourceName(source)}专业的字段，但可以查看`
                        }
                      </AlertDescription>
                    </Alert>
                  ) : (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>字段名称</TableHead>
                          <TableHead>描述</TableHead>
                          <TableHead>数据来源</TableHead>
                          <TableHead>数据类型</TableHead>
                          <TableHead>计量单位</TableHead>
                          <TableHead>当前值</TableHead>
                          <TableHead>状态</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {displayFields.map((field) => (
                          <TableRow key={field.id} className={field.canEdit ? "bg-green-50" : ""}>
                            <TableCell className="font-medium">
                              <div className="flex items-center gap-2">
                                {field.canEdit && <span className="text-green-600 text-sm">✓</span>}
                                <span data-field-name={field.field_name}>
                                  {Array.isArray(field.field_name) ? field.field_name[0] : field.field_name}
                                </span>
                              </div>
                              {process.env.NODE_ENV === 'development' && (
                                <div className="text-xs text-gray-400 mt-1">
                                  ID: {field.id} | 原始名称: "{field.field_name}" | 长度: {field.field_name.length}
                                </div>
                              )}
                            </TableCell>
                            <TableCell className="text-sm text-gray-600">
                              {field.field_description}
                            </TableCell>
                            <TableCell>
                              <Badge className={getDataSourceColor(field.data_source)}>
                                {field.data_source}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <Badge variant="outline">{field.data_type}</Badge>
                            </TableCell>
                            <TableCell>{field.measurement_unit}</TableCell>
                            <TableCell>
                              {field.canEdit ? (
                                <Input
                                  value={editData[field.id] || ''}
                                  onChange={(e) => updateFieldValue(field.id, e.target.value)}
                                  placeholder={field.example_description}
                                  className="w-full"
                                />
                              ) : (
                                <div className="flex items-center space-x-2">
                                  <span className="text-gray-600">
                                    {editData[field.id] || field.parameter_value || '-'}
                                  </span>
                                  <Lock className="h-4 w-4 text-gray-400" />
                                </div>
                              )}
                            </TableCell>
                            <TableCell>
                              {field.canEdit ? (
                                <Badge variant="default" className="bg-green-100 text-green-800">
                                  <CheckCircle className="h-3 w-3 mr-1" />
                                  可编辑
                                </Badge>
                              ) : (
                                <Badge variant="secondary" className="bg-gray-100 text-gray-600">
                                  <Lock className="h-3 w-3 mr-1" />
                                  只读
                                </Badge>
                              )}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  )}
                </TabsContent>
              )
            })}
            </Tabs>
          ) : (
            <Alert>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                当前专业没有可显示的字段数据
              </AlertDescription>
            </Alert>
          )}
        </CardContent>
      </Card>

      {/* 保存按钮 */}
      {editableCount > 0 && (
        <div className="flex justify-end">
          <Button onClick={handleSave} disabled={saving}>
            {saving ? (
              <div className="flex items-center space-x-2">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                <span>保存中...</span>
              </div>
            ) : (
              <div className="flex items-center space-x-2">
                <Save className="h-4 w-4" />
                <span>保存参数</span>
              </div>
            )}
          </Button>
        </div>
      )}
    </div>
  )
}
